<template>
  <view class="container">
    <view v-if="isLoading" class="loading">
      <u-loading-icon mode="circle" />
    </view>
    <view v-else class="field-body" @click="handleSelect()">
      <view class="field-value oneline-hide">
        {{ valueText ? valueText: placeholder }}
        <image class="icon" :src="getIcon()" />
      </view>
    </view>
    <u-picker :show="show" ref="uPicker" :columns="options" keyName="name" :defaultIndex="defaultValue" @change="changeHandler" @cancel="show = false" @confirm="onConfirm" />
  </view>
</template>

<script>
  import Emitter from '@/plugin/uview-ui/libs/util/emitter.js'
  import RegionModel from '@/common/model/Region'

  export default {
    name: 'SelectRegion',
    mixins: [Emitter],
    model: {
      prop: 'value',
      event: 'change'
    },
    props: {
      column:{
        type: Number,
        default: 3
      },
      searchtIcon:{
        type: Boolean,
        default: false
      },
      // v-model 指定选中项
      value: {
        type: Array,
        default: () => {
          return []
        }
      },
      defaultval:{
        type: Array,
        default: () => {
          return []
        }
      },
      // 未选中时的提示文字
      placeholder: {
        type: String,
        default: '请选择省/市/区'
      }
    },
    data() {
      return {
        // 正在加载
        isLoading: true,
        // 是否显示
        show: false,
        // 默认选中的值
        defaultValue: [7,4,4],
        // 选中项内容(文本展示)
        valueText: '',
        // 级联选择器数据
        options: [],
        treeData:[]
      }
    },
    watch: {
      // 监听v-model
      value(val) {
        // 设置默认选中的值
        this.valueText = val.map(item => item.name).join('/')
        // 将当前的值发送到 u-form-item 进行校验
        this.dispatch('u-form-item', 'on-form-change', val)
      },
    },
    created() {
      this.defaultValue = this.column == 3 ? [7,4,4] : [7,4]
      // 获取地区数据
      this.getTreeData()
    },
    methods: {
      getIcon(){
        if(this.searchtIcon){
          return this.$Config.get('imageUrl')+'/data/search.png'
        }else{
          return this.$Config.get('imageUrl')+'/order/address_right.png'
        }
      },
      // 打开选择器
      handleSelect() {
        this.show = true
      },

      // 获取地区数据
      getTreeData() {
        const app = this
        app.isLoading = true
        RegionModel.getRegionList()
          .then(regions => {
            // 格式化级联选择器数据
            this.treeData = regions;
            if(this.defaultval.length > 0){
              this.setDefault()
            }
            this.options = this.getOptions()
          })
          .finally(() => app.isLoading = false)
      },
      changeHandler(e){
        const {columnIndex,indexs,value,picker = this.$refs.uPicker} = e;
        let returnIndex = this.column == 3 ? 2 : 1;
        if(columnIndex == returnIndex){
          return;
        }
        const options = this.getOptions(indexs);
        if(columnIndex == 0) {
          picker.setColumnValues(1, options[1])
          if(this.column == 3){
            picker.setColumnValues(2, options[2])
          }
        }else if(columnIndex == 1 && this.column == 3){
          picker.setColumnValues(2, options[2])
        }
      },
      // 确认选择后的回调
      onConfirm(e) {
        // 绑定到v-model执行的值
        this.$emit('input', e.value)
        this.$emit('change', e.value)
        this.show = false
      },
      /**
       * 格式化级联选择器数据
       * @param {*} regions 地区数据
       * 1,32,376
       */
      getOptions(defaultVals){
        const regions = this.treeData;
        const option1 = regions;
        let option2 = [];
        let option3 = [];
        if(defaultVals != undefined){
          option2 = regions[defaultVals[0]].children;
        }else{
          option2 = regions[0].children;
        }
        if(this.column == 3){
          if(defaultVals != undefined){
            option3 = option2[defaultVals[1]].children;
          }else{
            option3 = option2[0].children;
          }
        }

        return this.column  == 3 ? [option1,option2,option3] : [option1,option2]
      },
      setDefault() {
        const regions = this.treeData;
        const val = this.defaultval;
        const val1 = regions.findIndex(item => item.id == val[0]);
        const val2 = regions[val1].children.findIndex(item => item.id == val[1]);
        let value = [regions[val1],regions[val1].children[val2]]
        let defaultValue = [val1,val2]
        if(this.column == 3){
          const val3 = regions[val1].children[val2].children.findIndex(item => item.id == val[2]);
          value = [regions[val1],regions[val1].children[val2],regions[val1].children[val2].children[val3]]
          defaultValue = [val1,val2,val3]
        }
        this.defaultValue = defaultValue;
        this.$emit('input', value)
        this.$emit('change', value)
        // this.value = [regions[val1],regions[val1].children[val2],regions[val1].children[val2].children[val3]]
      },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
  }
  .field-value{
    line-height: 92rpx;
    background: #F2F2F2;
    border-radius: 16rpx;
    padding: 0 32rpx !important;
    font-size: 32rpx;
    font-weight: 500;
    color: #242323;
    border-width: 0 !important;
    position: relative;
    .icon{
      top: 34rpx;
      right: 32rpx;
      position: absolute;
      width: 24rpx;
      height: 24rpx;
      image{
        width: 100%;
        height: 100%;
      }
    }
  }
  .loading {
    padding-left: 10rpx;
    // text-align: center;
  }
</style>
